package sample.api.client;

import com.google.gson.Gson;
import org.dreamwork.gson.GsonHelper;
import org.dreamwork.misc.Base64;
import org.dreamwork.secure.SecureUtil;
import org.dreamwork.util.StringUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2014/12/22
 * Time: 21:11
 */
public class LoginTest extends RestfulAPIClient {
    public LoginTest () throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
        pattern = "user/login";
        method = HttpMethod.Post;
        encrypted = true;

        RestfulApiContext.setPublicKey (loadPublicKey ());

        com.google.gson.Gson g = org.dreamwork.gson.GsonHelper.getGson (true, true);
    }

    private PublicKey loadPublicKey () throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        File file = new File ("d:/tmp/keys/rsa_public_key.pem");
        FileReader fr = new FileReader (file);
        BufferedReader reader = new BufferedReader (fr);
        String line;
        StringBuilder builder = new StringBuilder ();
        while ((line = reader.readLine ()) != null) {
            if (!line.startsWith ("--"))
                builder.append (line.trim ());
        }

        byte[] data = Base64.decode (builder.toString ().trim ());
        X509EncodedKeySpec spec = new X509EncodedKeySpec (data);
        KeyFactory factory = KeyFactory.getInstance ("rsa");
        return factory.generatePublic (spec);
    }

    public static void main (String[] args) throws Exception {
        System.setProperty (SecureUtil.KEY_SECURE_PROVIDER, "org.bouncycastle.jce.provider.BouncyCastleProvider");
        LoginTest test = new LoginTest ();
        test.setBody ("{\"userId\":21,\"storeId\":\"31011500015\",\"password\":\"1234567890\",\"shortNumber\":\"PUK4\"}");
        String result = test.call ();
        System.out.println (result);
    }
}